﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;

namespace Admin.NET.Application;

/// <summary>
/// 调拨管理服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class AllocateService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Allocate> _allocateRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public AllocateService(SqlSugarRepository<Allocate> allocateRep, ISqlSugarClient sqlSugarClient)
    {
        _allocateRep = allocateRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询调拨管理 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询调拨管理")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<AllocateOutput>> Page(PageAllocateInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _allocateRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.AllocateCode.Contains(input.Keyword) || u.Remark.Contains(input.Keyword) || u.Details.Contains(input.Keyword) || u.UploadAttachments.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.AllocateCode), u => u.AllocateCode.Contains(input.AllocateCode.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remark), u => u.Remark.Contains(input.Remark.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Details), u => u.Details.Contains(input.Details.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.UploadAttachments), u => u.UploadAttachments.Contains(input.UploadAttachments.Trim()))
            .WhereIF(input.AllocateTypeId != null, u => u.AllocateTypeId == input.AllocateTypeId)
            .WhereIF(input.AllocateTimeRange?.Length == 2, u => u.AllocateTime >= input.AllocateTimeRange[0] && u.AllocateTime <= input.AllocateTimeRange[1])
            .WhereIF(input.WarehouseUPid != null, u => u.WarehouseUPid == input.WarehouseUPid)
            .WhereIF(input.WarehouseEnter != null, u => u.WarehouseEnter == input.WarehouseEnter)
            .WhereIF(input.Attn != null, u => u.Attn == input.Attn)
            .LeftJoin<Allocatetype>((u, allocateType) => u.AllocateTypeId == allocateType.Id)
            .LeftJoin<Warehouse>((u, allocateType, warehouseUP) => u.WarehouseUPid == warehouseUP.Id)
            .LeftJoin<UserManagement>((u, allocateType, warehouseUP, attn) => u.Attn == attn.Id)
            .Select((u, allocateType, warehouseUP, attn) => new AllocateOutput
            {
                Id = u.Id,
                AllocateCode = u.AllocateCode,
                AllocateTypeId = u.AllocateTypeId,
                AllocateTypeFkDisplayName = $"{allocateType.AllocateTypeName}",
                AllocateTime = u.AllocateTime,
                WarehouseUPid = u.WarehouseUPid,
                WarehouseUPFkDisplayName = $"{warehouseUP.WarehouseName}",
                WarehouseEnter = u.WarehouseEnter,
                Attn = u.Attn,
                AttnFkDisplayName = $"{attn.UserName}",
                Remark = u.Remark,
                Details = u.Details,
                UploadAttachments = u.UploadAttachments,
                IsDelete = u.IsDelete,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取调拨管理详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取调拨管理详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Allocate> Detail([FromQuery] QueryByIdAllocateInput input)
    {
        return await _allocateRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加调拨管理 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加调拨管理")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddAllocateInput input)
    {
        var entity = input.Adapt<Allocate>();
        return await _allocateRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新调拨管理 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新调拨管理")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateAllocateInput input)
    {
        var entity = input.Adapt<Allocate>();
        await _allocateRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除调拨管理 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除调拨管理")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteAllocateInput input)
    {
        var entity = await _allocateRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _allocateRep.FakeDeleteAsync(entity);   //假删除
        //await _allocateRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除调拨管理 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除调拨管理")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteAllocateInput> input)
    {
        var exp = Expressionable.Create<Allocate>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _allocateRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _allocateRep.FakeDeleteAsync(list);   //假删除
        //return await _allocateRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataAllocateInput input)
    {
        var allocateTypeIdData = await _allocateRep.Context.Queryable<Allocatetype>()
            .InnerJoinIF<Allocate>(input.FromPage, (u, r) => u.Id == r.AllocateTypeId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.AllocateTypeName}"
            }).ToListAsync();
        var warehouseUPidData = await _allocateRep.Context.Queryable<Warehouse>()
            .InnerJoinIF<Allocate>(input.FromPage, (u, r) => u.Id == r.WarehouseUPid)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.WarehouseName}"
            }).ToListAsync();
        var attnData = await _allocateRep.Context.Queryable<UserManagement>()
            .InnerJoinIF<Allocate>(input.FromPage, (u, r) => u.Id == r.Attn)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.UserName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "allocateTypeId", allocateTypeIdData },
            { "warehouseUPid", warehouseUPidData },
            { "attn", attnData },
        };
    }
    
    /// <summary>
    /// 导出调拨管理记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出调拨管理记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageAllocateInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportAllocateOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "调拨管理导出记录");
    }
    
    /// <summary>
    /// 下载调拨管理数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载调拨管理数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportAllocateOutput>(), "调拨管理导入模板", (_, info) =>
        {
            if (nameof(ExportAllocateOutput.AllocateTypeFkDisplayName) == info.Name) return _allocateRep.Context.Queryable<Allocatetype>().Select(u => $"{u.AllocateTypeName}").Distinct().ToList();
            if (nameof(ExportAllocateOutput.WarehouseUPFkDisplayName) == info.Name) return _allocateRep.Context.Queryable<Warehouse>().Select(u => $"{u.WarehouseName}").Distinct().ToList();
            if (nameof(ExportAllocateOutput.AttnFkDisplayName) == info.Name) return _allocateRep.Context.Queryable<UserManagement>().Select(u => $"{u.UserName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入调拨管理记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入调拨管理记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportAllocateInput, Allocate>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 调拨类型
                    var allocateTypeIdLabelList = pageItems.Where(x => x.AllocateTypeFkDisplayName != null).Select(x => x.AllocateTypeFkDisplayName).Distinct().ToList();
                    if (allocateTypeIdLabelList.Any()) {
                        var allocateTypeIdLinkMap = _allocateRep.Context.Queryable<Allocatetype>().Where(u => allocateTypeIdLabelList.Contains($"{u.AllocateTypeName}")).ToList().ToDictionary(u => $"{u.AllocateTypeName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.AllocateTypeId = allocateTypeIdLinkMap.GetValueOrDefault(e.AllocateTypeFkDisplayName ?? "");
                            if (e.AllocateTypeId == null) e.Error = "调拨类型链接失败";
                        });
                    }
                    // 链接 调出仓库
                    var warehouseUPidLabelList = pageItems.Where(x => x.WarehouseUPFkDisplayName != null).Select(x => x.WarehouseUPFkDisplayName).Distinct().ToList();
                    if (warehouseUPidLabelList.Any()) {
                        var warehouseUPidLinkMap = _allocateRep.Context.Queryable<Warehouse>().Where(u => warehouseUPidLabelList.Contains($"{u.WarehouseName}")).ToList().ToDictionary(u => $"{u.WarehouseName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.WarehouseUPid = warehouseUPidLinkMap.GetValueOrDefault(e.WarehouseUPFkDisplayName ?? "");
                            if (e.WarehouseUPid == null) e.Error = "调出仓库链接失败";
                        });
                    }
                    // 链接 经办人
                    var attnLabelList = pageItems.Where(x => x.AttnFkDisplayName != null).Select(x => x.AttnFkDisplayName).Distinct().ToList();
                    if (attnLabelList.Any()) {
                        var attnLinkMap = _allocateRep.Context.Queryable<UserManagement>().Where(u => attnLabelList.Contains($"{u.UserName}")).ToList().ToDictionary(u => $"{u.UserName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.Attn = attnLinkMap.GetValueOrDefault(e.AttnFkDisplayName ?? "");
                            if (e.Attn == null) e.Error = "经办人链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<Allocate>>();
                    
                    var storageable = _allocateRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.AllocateCode?.Length > 32, "调拨单号长度不能超过32个字符")
                        .SplitError(it => it.Item.Remark?.Length > 32, "备注长度不能超过32个字符")
                        .SplitError(it => it.Item.Details?.Length > 32, "调拨明细长度不能超过32个字符")
                        .SplitError(it => it.Item.UploadAttachments?.Length > 2000, "上传附件长度不能超过2000个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
